﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace System.ComponentModel
{
    class AbortableBackgroundWorker : BackgroundWorker
    {
        public AbortableBackgroundWorker()
        {
            this.WorkerSupportsCancellation = true;
            this.WorkerReportsProgress = true;
        }
        
        public object Tag { get; set; }
        private Thread workerThread;

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            //di thread yang berbeda.
            workerThread = Thread.CurrentThread;
            try
            {
                base.OnDoWork(e);
                workerThread = null;
            }
            catch (ThreadAbortException)
            {
                e.Cancel = true;
                Thread.ResetAbort();
            }
        }
        
        public void Abort()
        {
            if (!IsBusy) return;
            this.CancelAsync();
            try
            {
                if (workerThread != null)
                {
                    workerThread.Abort();
                    workerThread = null;
                }
            }
            catch { }
        }
    }
}
